package com.gavinandre.mvpsocketclient.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.gavinandre.mvpsocketclient.R;
import com.gavinandre.socket.ServerTarget;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SocketDemoActivity extends AppCompatActivity implements ServerTarget.OnUpdataListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_demo);
        init();

        new Thread(new Runnable() {
            @Override
            public void run() {
                initView();
            }
        }).start();


    }
    Button  send;
    TextView textView;
    EditText editText;
    private void init( ) {

        send = findViewById(R.id.button_server_id);

        textView = findViewById(R.id.textview_server);

        editText = findViewById(R.id.edit_server_input);


    }

    private void initView() {
        PrintWriter pw = null;
        Scanner scan = null;
        ServerSocket ss = null;
        Socket socket = null;
        try {
            //创建服务端
            ss = new ServerSocket(10086);
            System.out.println("启动服务！");

            //等待客户端连接，获取客户端对象
            socket = ss.accept();

            //开启一个子线程，用于自动接收客户端发来的消息
            ServerTarget st = new ServerTarget(socket);
            Thread t = new Thread(st);

            st.setOnUpdataListener(this);

            t.start();


            //获取服务端的键盘监听
            scan = new Scanner(System.in);

            //获取用于发送消息的打印流
            pw = new PrintWriter(socket.getOutputStream(), true);//自动刷新

            while(true){
                System.out.println("请输入消息内容：");
            //    String serverMsg = scan.nextLine();//获取服务端键盘输入的内容

                String serverMsg = editText.getText().toString().trim();//获取服务端键盘输入的内容
                pw.println(serverMsg);//发送消息

            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //关闭资源
            try {
                pw.close();
                scan.close();
                socket.close();
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //拿到了客户端发来的消息
    @Override
    public void upDataUI(String message) {

        textView.setText(message);

    }
}
